import { axios } from "@/plugins/axios"
import * as types from "./mutation_types"

const actions = {
  
  getUserSystemRoles({ commit, state }, force = false) {
    const url = process.env.VUE_APP_API_URL + "api/v1/user/roles"
    if (state.isSystemRolesFetched != null && !force) {
      return state.isSystemRolesFetched.then((_) => {
        return state.userSystemRoles
      })
    } else {
      const waitableFetch = new Promise((resolve) => {
        this.SystemRolesResolver = resolve
      })
      commit("setSystemRolesFetchedLock", waitableFetch)
      return axios.get(url).then((res) => {
        const roles = res.data.roles
        commit(types.CURRENT_SYSTEM_ROLE_UPDATE, roles)
        this.SystemRolesResolver(true)
        return roles
      })
    }
  },
}

function initialState() {
  return {
    userSystemRoles: [],
    isSystemRolesFetched: null,
  }
}
const state = initialState()

const getters = {}

const mutations = {
  setSystemRolesFetchedLock(state, waitableFetch) {
    // 传递一个promise对象，返回已获取的值，避免并行竞争问题
    state.isSystemRolesFetched = waitableFetch
  },
  [types.CURRENT_SYSTEM_ROLE_UPDATE](state, roles) {
    state.userSystemRoles = []
    state.userSystemRoles = [...roles]
  },
  [types.CURRENT_SYSTEM_ROLE_RESET](state) {
    state.userSystemRoles = []
    state.isSystemRolesFetched = null
  },
}

export default {
  namespaced: true,
  state,
  getters,
  actions,
  mutations,
}
